import time

from curl_cffi.requests import AsyncSession


async def get_trade(session: AsyncSession, code: str, count: int = 10):
    params = {
        "symbol": code,
        "count": count
    }
    resp = await session.get("https://stock.xueqiu.com/v5/stock/history/trade.json", params=params)
    data = resp.json()
    return data['data']['items']


def trade_data_analysis(data):
    results = []
    for item in data:
        results.append({
            "tp": item['current'],
            "tc": item['trade_volume'],
            "ta": int(round(item['current'] * item['trade_volume'], 0)),
            "tt": item['side'],
            'percent': item['percent']
        })
    return results


async def get_pankou(session: AsyncSession, code: str):
    params = {
        "symbol": code,
    }
    resp = await session.get("https://stock.xueqiu.com/v5/stock/realtime/pankou.json", params=params)
    data = resp.json()
    bp1 = data['data']['bp1'] or 0
    bc1 = data['data']['bc1'] or 0
    sp1 = data['data']['sp1'] or 0
    sc1 = data['data']['sc1'] or 0
    return {
        "timestamp": data['data']['timestamp'],
        "current": data['data']['current'],
        "bp1": bp1,
        "bc1": bc1,
        "ba1": int(round(bp1 * bc1, 0)),
        "sp1": sp1,
        "sc1": sc1,
        "sa1": int(round(sp1 * sc1, 0)),
    }


async def suggest_stock(session: AsyncSession, q: str):
    params = {
        "q": q,
    }
    resp = await session.get("https://xueqiu.com/query/v1/suggest_stock.json", params=params)
    data = resp.json()
    return data['data']


async def realtime_quotec(session: AsyncSession, codes: list):
    params = {
        "symbol": ",".join(codes),
        "_": str(int(time.time() * 1000))
    }
    resp = await session.get("https://xueqiu.com/v5/stock/realtime/quotec.json", params=params)
    data = resp.json()
    return data['data']


async def comment(session: AsyncSession, symbol: str, page=1, page_size: int = 10):
    """获取评论"""
    params = {
        'count': str(page_size),
        'comment': '0',
        'symbol': symbol,
        'hl': '0',
        'source': 'all',
        'sort': '',
        'page': str(page),
        'q': '',
        'type': '11',
    }

    resp = await session.get('https://xueqiu.com/query/v1/symbol/search/status.json', params=params)
    data = resp.json()
    return data['list']


async def user_timeline(session: AsyncSession, page=1, user_id: str = "1218465053"):
    """获取评论"""
    params = {
        "page": str(page),
        "user_id": user_id
    }

    resp = await session.get('https://xueqiu.com/v4/statuses/user_timeline.json', params=params)
    data = resp.json()
    print(data)
    return data['statuses']
